package com.pine.common;

import com.pine.functioninterface.IMyLambda;
import com.pine.sort.ISort;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class EfficiencyTest {

    /**
     * 测试算法性能
     * @param num 循环测试次数
     * @param lambda 表达式
     * @return 总耗时
     */
    public static double nanoTimeTest(int num, IMyLambda lambda) {
        long prev = System.nanoTime();
        for (int i = 0; i < num; i++) {
            lambda.invoke();
        }
        long end = System.nanoTime();
        double result = (end - prev) / 1000000000.0d;
        return result;
    }

    /**
     * 利用反射测试排序方法
     * @param num
     * @param obj
     * @param dataArr
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static double nanoTime(int num, Object obj, Object dataArr) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> cls = obj.getClass();
        Constructor<?> constructor = cls.getConstructor();
        ISort iSort = (ISort) constructor.newInstance();
        Method sort = cls.getMethod("sort", Comparable[].class);
        double result = nanoTimeTest(num, () -> {
            try {
                sort.invoke(iSort, dataArr);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        });
        return result;
    }
}
